import logging

from django.shortcuts import render

# Create your views here.
from .models import User
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import JsonResponse


# 注册
@api_view(['POST'])
def adduser(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    gender = data.get('gender')
    age = data.get('age')
    User(name=name, gender=gender, age=age).save()
    return JsonResponse({
        'code': 200,
        'msg': '注册成功'
    })


from django.core.paginator import PageNotAnInteger, Paginator, EmptyPage


# 用户列表
@api_view(['get'])
def getuserinfo(request):
    flag, name = checktoken(request)
    if flag is False:
        return JsonResponse({
            'code': 404,
            'msg': '未登录，请先登录',
        })
    page = request.GET.get('page')
    pageSize = request.GET.get('pageSize')
    logging.info(f'查看前端传过的：{page, pageSize}')
    allobj = User.objects.filter().values()
    pageobjs = Paginator(allobj, pageSize)
    try:
        stringlepageobj = pageobjs.page(page)
    except EmptyPage:
        stringlepageobj = pageobjs.page(pageobjs.num_pages)
    except PageNotAnInteger:
        stringlepageobj = pageobjs.page(1)
    lis = []
    for item in stringlepageobj.object_list:
        lis.append({
            'id': item.get('id'),
            'name': item.get('name'),
            'gender': item.get('gender'),
            'age': item.get('age'),
            'createtime': item.get('createtime'),
            'updatatime': item.get('updatatime'),
        })
    return JsonResponse({
        'code': 200,
        'data': lis,
        'items': allobj.count(),
    })


# 删除
@api_view(['delete'])
def deletedata(request, itemid):
    obj = User.objects.get(id=itemid)
    obj.delete()
    return JsonResponse({
        'code': 200,
        'msg': '删除成功',
    })


# 查询
@api_view(['get'])
def getuser(request, itemid):
    flag, name = checktoken(request)
    if flag is False:
        return JsonResponse({
            'code': 404,
            'msg': '未登录，请先登录',
        })
    obj = User.objects.get(id=itemid)
    return JsonResponse({
        'code': 200,
        'name': obj.name,
        'gender': obj.gender,
        'age': obj.age,
        'createtime': obj.createtime,
        'updatetime': obj.updatatime,
    })


# 修改
@api_view(['put'])
def updateitem(request, itemid):
    obj = User.objects.get(id=itemid)
    data = JSONParser().parse(request)
    name = data.get('name')
    gender = data.get('gender')
    age = data.get('age')
    obj.name = name
    obj.gender = gender
    obj.age = age
    obj.save()
    return JsonResponse({
        'code': 200,
        'msg': "修改成功",
    })


# 登录
@api_view(['post'])
def login(request):
    data = JSONParser().parse(request)
    name = data.get('username')
    password = data.get('password')
    if User.objects.filter(name=name).exists() is False:
        return JsonResponse({
            'code': 201,
            'msg': "用户名不存在"
        })
    obj = User.objects.get(name=name)
    if str(obj.age) != password:
        return JsonResponse({
            'code': 202,
            'msg': "密码不正确"
        })
    token = createtoken(name)
    return JsonResponse({
        'code': 200,
        'msg': "登录成功",
        'token': token
    })


import string, random
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta


# 创建token
def createtoken(name):
    randomstr = ''.join(random.choices(string.ascii_letters, k=8))
    token = Signer().sign(randomstr + name)
    cache.set(f"test_{name}", token, timeout=timedelta(minutes=100).total_seconds())
    return token


def checktoken(request):
    reqtoken = request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False, 'xxxx'
    untoken = Signer().unsign(reqtoken)
    name = untoken[8:]
    cachetoken = cache.get(f'test_{name}')
    if cachetoken is None:
        return False, 'xxxx'
    return True, name

# ll
def is_empty(n):
    return n is None or str(n).strip() == ''


def select_info(allobjs):
    lis = []
    for item in allobjs:
        lis.append({
            'id': item.id,
            'name': item.name,
            'gender': item.gender,
            'age': item.age,
            'createtime': item.createtime,
            'updatatime': item.updatatime,
        })
    return JsonResponse({
        'code': 200,
        'data': lis,
        'items': allobjs.count(),
    })


@api_view(['get'])
def getcondition(request):
    name = request.GET.get('name')
    gender = request.GET.get('gender')
    age = request.GET.get('age')
    logging.info(f'从vue端传过来的name：{name}')
    logging.info(f'从vue端传过来的gender：{gender}')
    logging.info(f'从vue端传过来的age：{age}')
    if is_empty(name) and is_empty(gender) and is_empty(age):
        return JsonResponse({'code': 404, 'msg': '请输入查询条件'})

    if is_empty(name) is False and is_empty(gender) is False and is_empty(age) is False:
        allobjs = User.objects.filter(name=name, gender=gender, age=age)
        return select_info(allobjs)
    if is_empty(name) is False and is_empty(gender) is True and is_empty(age) is True:
        allobjs = User.objects.filter(name=name)
        return select_info(allobjs)

    if is_empty(name) is True and is_empty(gender) is True and is_empty(age) is False:
        allobjs = User.objects.filter(age=age)
        return select_info(allobjs)

    if is_empty(name) is True and is_empty(gender) is False and is_empty(age) is True:
        allobjs = User.objects.filter(gender=gender)
        return select_info(allobjs)

    if is_empty(name) is False and is_empty(gender) is False and is_empty(age) is True:
        allobjs = User.objects.filter(gender=gender, name=name)
        return select_info(allobjs)

    if is_empty(name) is True and is_empty(gender) is False and is_empty(age) is False:
        allobjs = User.objects.filter(gender=gender, age=age)
        return select_info(allobjs)

    if is_empty(name) is False and is_empty(gender) is True and is_empty(age) is False:
        allobjs = User.objects.filter(name=name, age=age)
        return select_info(allobjs)


from django.db.models import Q, Max, Min, Sum, Count


@api_view(['get'])
def getgenderlist(request):
    gendervalues = User.objects.filter().values('gender').annotate(gender1=Max("gender"))
    logging.info(f"查看分组后的数据:{gendervalues}")
    lis = []
    for item in gendervalues:
        lis.append({
            'id': item.get('gender'),
            'name': item.get('gender')
        })
    return JsonResponse({
        'code': 200,
        'data': lis,
    })
